#!/usr/bin/env python

""" dueTasks  a tool for reading a taskpaper file and finding what tasks are
due that day, and printing them to the screen."""

import re
import os.path
from sys import stderr,stdout
from datetime import datetime
from taskpyper import TaskFile

__version__  = u"0.1.0.10"
# 0.1.0.10 - 

gDebug = True;

#:todo: hide this function from the outside world
def debugprint(*stuffToPrint):
	#Astric indicates that it can handle a list as input
	if (gDebug):
		print "DEBUG:" + " ".join(stuffToPrint)


		
def main():
	""" Main statement for running this as a command line tool.
Command line options are:
-i inputFileName  : input file to parse for things due today
-o outputFileName  : output file to parse for things due today. 
If file exists it's appended to,if no file exsits it is created. If the output filename is stdout,
the output is written to the command line"""

	from optparse import OptionParser;

	importFilename = "test.taskpaper" #default read-from
	outputFilename = None
	tpBlob = None
	targetDatetime = datetime.now()
	dueTasks = None
	
	debugprint('main')
	
	
	#Setup parser for cmd line values
	optParser = OptionParser()
	optParser.add_option("-i","--inputFilename",dest='inFilename',help="input file",type='string')
	optParser.add_option("-o","--outputFilename",dest='outFilename',help="output file",type='string')
	#:TODO: make this magic
	#optParser.add_option("-t","--tag",dest='tags',help="tags",type='string')

	
	#do the a parse
	debugprint('parsing')
	(option, arg) = optParser.parse_args();

	#Load the parsed values to local variables
	if(option.inFilename and option.inFilename != ""):
		importFilename = option.inFilename;
		debugprint('import filename')
	if(option.outFilename and option.outFilename != ""):
		outputFilename = option.outFilename;
		debugprint('write to file %s' %outputFilename)


	#load the tasks and get them
	if(importFilename):
		tpBlob =  TaskFile(importFilename)
		if tpBlob :
			dueTasks = tpBlob.findDue(targetDatetime)

	#default to print-to-stdout
	if dueTasks and (not outputFilename):
		outputFilename == 'stdout'

	#print or write to file the output
	if(outputFilename == 'stdout'):
		for task in dueTasks:
			print str(task)
	elif (outputFilename):
		debugprint('writing to %s' %outputFilename)

		print "else\n"
		try :
			print "trying\n"
			#check for existance
			openOpts = 'w'
			if(os.path.isfile(outputFilename)):	
				debugprint('file %s exists. appending' %(outputFilename))				
				openOpts = 'a'
			debugprint('write to file %s with opts %s' %(outputFilename, openOpts))
			fh = open(outputFilename, openOpts)
			if(fh):
				dateStr = targetDatetime.isoformat()
				fh.write("Due Today:\n")
				fh.write("\t(Autogenerated on %s)\n" %dateStr)
				for task in dueTasks:
					try :
						fh.write(str(task))
						fh.write("\n");
					except IOError, e:
						stderr.write("File access Fail\n");
				fh.close()
				del(fh);
		except IOError, e:
			stderr.write("File access Fail\n");


#if (__name__ == u"__main__"):
main()
